<template>
  <div class="statistics-container">
    <div class="stats-header">
      <h1>访问统计 <span class="subtitle">数据分析中心</span></h1>
      <div class="stats-cards">
        <div class="stat-card">
          <div class="stat-icon">
            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#4285f4" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
              <path d="M22 12h-4l-3 9L9 3l-3 9H2"></path>
            </svg>
          </div>
          <div class="stat-info">
            <h3>今日访问次数</h3>
            <p class="stat-value">{{ todayVisits }}</p>
          </div>
        </div>
      </div>
    </div>

    <div class="filter-controls">
      <button @click="filterMode = 'day'">按日显示</button>
      <button @click="filterMode = 'month'">按月显示</button>
      <button @click="filterMode = 'year'">按年显示</button>
    </div>

    <!-- 选择器 -->
    <div class="selector-controls" v-if="filterMode === 'day' || filterMode === 'month'">
      <template v-if="filterMode === 'day'">
        <label>选择月份：</label>
        <input type="month" v-model="selectedMonth" @change="updateChart(filterMode)" />
      </template>
      <template v-if="filterMode === 'month'">
        <label>选择年份：</label>
        <input type="number" v-model="selectedYear" min="2000" max="2100" @change="updateChart(filterMode)" />
      </template>
    </div>

    <div class="chart-container" ref="visitChart"></div>
  </div>
</template>


<style scoped>
.statistics-container {
  display: flex;
  flex-direction: column;
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.stats-header {
  margin-bottom: 20px;
}

.title-container {
  margin-bottom: 20px;
}

h1 {
  color: #333;
  font-size: 24px;
  margin: 0;
  display: flex;
  align-items: center;
}

.subtitle {
  font-size: 14px;
  color: #888;
  margin-left: 10px;
  font-weight: normal;
}

.stats-cards {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  display: flex;
  align-items: center;
  background-color: white;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  flex: 1;
  transition: transform 0.3s, box-shadow 0.3s;
}

.stat-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background-color: #f0f7ff;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
}

.stat-info h3 {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.stat-value {
  margin: 5px 0 0 0;
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.filter-controls {
  margin: 20px 0;
  display: flex;
  gap: 10px;
}

button {
  flex: 1;
  padding: 8px 0;
  background-color: #f0f0f0;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

button:hover {
  background-color: #e0e0e0;
}

.chart-container {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  flex: 1;
  min-height: 400px;
}

.selector-controls {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.selector-controls input {
  padding: 5px 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

</style>

<script setup>
import { ref, onMounted, watch, onUnmounted, markRaw } from 'vue';
import axios from 'axios';
import * as echarts from 'echarts';

const todayVisits = ref(0);
const visitChart = ref(null);
const allVisits = ref({});
const filterMode = ref('day');
const chartInstance = ref(null);
const selectedMonth = ref(new Date().toISOString().slice(0, 7));
const selectedYear = ref(new Date().getFullYear());

// 记录访问
const recordVisit = async () => {
  try {
    const response = await axios.get('http://localhost:8080/visit');
    console.log(response.data);
  } catch (error) {
    console.error('记录访问失败：', error);
  }
};

// 获取今日访问次数
const fetchTodayVisits = async () => {
  try {
    const response = await axios.get('http://localhost:8080/today-visits');
    todayVisits.value = response.data;
  } catch (error) {
    console.error('获取访问次数失败：', error);
  }
};

// 获取所有访问记录
const fetchAllVisits = async () => {
  try {
    const response = await axios.get('http://localhost:8080/get-all-visits');
    allVisits.value = response.data;
    updateChart(filterMode.value);
  } catch (error) {
    console.error('获取所有访问记录失败：', error);
  }
};

// 页面加载时记录访问并获取访问次数
onMounted(async () => {
  const visitId = sessionStorage.getItem('visitId');
  const today = new Date();
  const newVisitId = today.toDateString();
  console.log(newVisitId);
  if (!visitId || visitId !== newVisitId) {
    sessionStorage.setItem('visitId', newVisitId);
    await recordVisit();
  }
  await fetchTodayVisits();
  await fetchAllVisits();
  initChart();
});

// 初始化 ECharts 图表
const initChart = () => {
  if (visitChart.value) {
    // 使用 markRaw 包裹 echarts.init 的返回值，避免响应式观测
    chartInstance.value = markRaw(echarts.init(visitChart.value));
    updateChart(filterMode.value);

    // 添加窗口大小变化时的图表调整
    const handleResize = () => {
      if (chartInstance.value) {
        chartInstance.value.resize();
      }
    };

    window.addEventListener('resize', handleResize);

    // 在组件卸载时移除监听器
    onUnmounted(() => {
      window.removeEventListener('resize', handleResize);
      if (chartInstance.value) {
        chartInstance.value.dispose(); // 销毁图表实例
        chartInstance.value = null;
      }
    });
  }
};

// 当筛选模式改变时更新图表
watch(filterMode, (newMode) => {
  updateChart(newMode);
});

// 更新图表数据
const updateChart = (mode) => {
  const data = allVisits.value;
  if (!data || Object.keys(data).length === 0) return;

  let aggregatedData = {};
  const dates = Object.keys(data).sort();

  if (mode === 'day') {
    const monthFilter = selectedMonth.value;
    dates.forEach(date => {
      if (date.startsWith(monthFilter)) {
        aggregatedData[date] = data[date];
      }
    });
  } else if (mode === 'month') {
    const yearFilter = selectedYear.value.toString();
    dates.forEach(date => {
      if (date.startsWith(yearFilter)) {
        const [year, month] = date.split('-');
        const monthKey = `${year}-${month}`;
        if (aggregatedData[monthKey]) {
          aggregatedData[monthKey] += data[date];
        } else {
          aggregatedData[monthKey] = data[date];
        }
      }
    });
  } else if (mode === 'year') {
    dates.forEach(date => {
      const [year] = date.split('-');
      if (aggregatedData[year]) {
        aggregatedData[year] += data[date];
      } else {
        aggregatedData[year] = data[date];
      }
    });
  }

  const aggregatedDates = Object.keys(aggregatedData).sort();
  const aggregatedValues = Object.values(aggregatedData);

  const option = {
    title: {
      text: '访问趋势',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: (params) => `${params.name}: ${params.value} 次`
    },
    xAxis: {
      type: 'category',
      data: aggregatedDates,
      axisLabel: {
        rotate: mode === 'day' ? 45 : 0
      }
    },
    yAxis: {
      type: 'value'
    },
    series: [{
      data: aggregatedValues,
      type: 'line',
      smooth: true,
      lineStyle: { width: 3, color: '#4285f4' },
      itemStyle: { color: '#4285f4' },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: 'rgba(66, 133, 244, 0.3)' },
          { offset: 1, color: 'rgba(66, 133, 244, 0.05)' }
        ])
      }
    }]
  };

  if (chartInstance.value) {
    chartInstance.value.setOption(option);
  }
};
</script>